package business.basic;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 数据库连接类，基于对应jdbc驱动程序实现数据库的连接和断开
 * @author 
 *@version 2019-3-4
 */

public class DBConnection {
	String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
	String url = "jdbc:sqlserver://localhost:1433;DatabaseName=BookDB";
	String user = "sa";
	String pwd = "123456";
	/**
	 * 根据DBConnection中设定的数据库连接参数实现数据库连接，并返回一个指定的Connection对象
	 * @return
	 * @throws Exception
	 */
	
	public Connection getConnection() throws Exception{
		Class.forName(driverName);
		
		Connection con = DriverManager.getConnection(url, user, pwd);
		return con;
	}
	/**
	 * 将通过参数传入的Connection对象进行关闭操作
	 * @param con 要关闭的Connection对象
	 */
	public void closeConnection(Connection con,Statement ptmt,java.sql.ResultSet rs){
		try {
			if(rs!=null){
				rs.close();
			}
			if(ptmt!=null){
				ptmt.close();
			}
			if (con != null) {
				con.close();
			}
		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

  	public static void main(String args[]){
  		Connection con=null;
		DBConnection dbc=new DBConnection();
		try {
			con = dbc.getConnection();
			dbc.closeConnection(con, null, null);
			System.out.println("213");
		} catch (Exception e) {
			e.printStackTrace();
			dbc.closeConnection(con, null, null);
			System.out.println("111");
		}
	}
 
		
}
